<?php
namespace app\stores\model\order;
use app\beautiful\model\finance\SettleOrderModel;
use app\beautiful\model\member\MemberCouponModel;
use app\beautiful\model\member\MemberModel;
use app\beautiful\model\order\OrderRefundModel;
use app\common\model\CommonModel;
use app\common\model\ShopModel;
use think\facade\Db;

class BuyOrderModel extends CommonModel{
    protected  $name = 'beautiful_buy_order';
    protected  $pk   = 'buy_order_id';
    protected $type=[
        'pay_info' => 'array',
    ];


    public function shop(){

        return  $this->hasOne(ShopModel::class,'shop_id','shop_id');

    }
    public function member(){

        return  $this->hasOne(MemberModel::class,'member_id','member_id');

    }

    public function memberCoupon(){

        return  $this->hasOne(MemberCouponModel::class,'member_coupon_id','member_coupon_id');

    }
    public function getPayTimeFormatAttr($value,$data){

        return $data['pay_time'] ? date('Y-m-d H:i:s',$data['pay_time']) : '-';

    }
    public function getAddTimeFormatAttr($value,$data){

        return $data['add_time'] ? date('Y-m-d H:i:s',$data['add_time']) : '-';

    }
    public function getPriceAttr($value,$data)
    {
        return round(($data['balance']*100 - $data['vip_balance']*100 - $data['coupon_money']*100 - $data['integral_balance']*100)/100,2);
    }

    public function getDiscountMoneyAttr($value,$data)
    {
        return round(($data['vip_balance']*100 + $data['coupon_money']*100 + $data['integral_balance']*100)/100,2);
    }

    public function getDiscountAttr($value,$data)
    {
        return round((($data['balance']*100 - $data['vip_balance']*100)/($data['balance']*100))*10,2);
    }

    public function getPayTypeMeanAttr($value,$data)
    {
        $type_means=[
            'weixin'=>'微信支付',
            'platform_money'=>'钱包支付',
            'money'=>'储值卡支付',
            'offline' => '线下补单',
        ];
        if(isset($data['mix_pay_type']) && $data['mix_pay_type']){
            $mix_pay_type = explode(',',$data['mix_pay_type']);
            $str = '';
            for($i=0;$i<count($mix_pay_type);$i++){
                $pay_type = $mix_pay_type[$i];
                if($type_means[$pay_type]){
                    $str.=$type_means[$pay_type].',';
                }
            }
            $str = trim($str,",");
            return $str ?? '-';
        }else{
            return $type_means[$data['pay_type']] ?? '-';
        }


    }
    public function getMixPayTypeMeanAttr($value,$data)
    {
        $pay_type = $data[''];
        $type_means=[
            'weixin'=>'微信支付',
            'platform_money'=>'钱包支付',
            'money'=>'储值卡支付',
            'offline' => '线下补单',
        ];
        return $type_means[$data['pay_type']] ?? '-';
    }
    public function refundLogs(){

        return  $this->hasMany(OrderRefundModel::class,'buy_order_id','buy_order_id');

    }
    public  function list($where,$order,$page=1,$limit=10){
        $query = Db::name('beautiful_buy_order')->alias('bo')
            ->join('beautiful_member m','m.member_id=bo.member_id')
            ->join('beautiful_member_level ml','ml.member_id=m.member_id')
            ->leftJoin('beautiful_level l','l.level_id=ml.level_id')
            ->leftJoin('beautiful_settle_order so','so.b_order_id=bo.buy_order_id')
            ->when(isset($where['start_time']),function ($query) use ($where){
                $query->where('bo.add_time>='.$where['start_time']);
            })
            ->when(isset($where['end_time']),function ($query) use ($where){
                $query->where('bo.add_time<='.$where['end_time']);
            })
            ->when(!empty($where['shop_id']),function ($query) use ($where){
                $query->where(['bo.shop_id'=>$where['shop_id']]);
            })
            ->when(!empty($where['is_paid']),function ($query) use ($where){
                $query->where(['bo.is_paid'=>$where['is_paid']]);
            })
            ->when(isset($where['is_settle']),function ($query) use ($where){
                $query->where(['bo.is_settle'=>$where['is_settle']]);
            })
            ->when(isset($where['b_order_ids']),function ($query) use ($where){
                $query->whereIn('bo.buy_order_id',$where['b_order_ids']);
            })
            ->field("so.settle_money,so.b_order_id,bo.vip_balance,bo.refund_money,bo.buy_order_id,bo.balance as total_price,bo.discount_detail,bo.member_coupon_id,bo.pay_type,bo.pay_money as need_pay,bo.coupon_money,bo.status,bo.refund_money,m.nick_name,m.member_num,m.mobile,m.face,l.name as level_name");
        $query=$query->order($order)->group('bo.buy_order_id');
        $count = $query->count();
        $list= $query->limit($limit)->page($page)
            ->select()
            ->toArray();
        foreach ($list as &$v){
            $return = $this->buyYouhui($v);
            $v['settle_money'] = sprintf("%.2f",$v['settle_money']);
            $v['youhui_name'] = $return['youhui_name'];
            $v['youhui'] = $return['youhui'];
            $v['pay_type_means'] = $this->getPayTypeMeanAttr('',$v);
            //商户结算
            $settle = SettleOrderModel::where(['b_order_id'=>$v['buy_order_id']])->find();
            $v['settle_money'] = $settle?sprintf("%.2f",$settle['settle_money']):0;
            //是否已全退款
            $v['is_bf_refund'] = ($v['refund_money']>0 && $v['status']!=3)?1:0;
            $v['need_pay'] = sprintf("%.2f",$v['need_pay'] - $v['refund_money']);
            $v['youhui_price'] = $v['vip_balance'];
        }

        return compact('count','list');
    }
    function buyYouhui($datas){
        $youhui_name = '';
        $youhui = [];
        //优惠券折扣
        if($datas['member_coupon_id']>0){
            $coupon = MemberCouponModel::with(['couponInfo'])->where(['member_coupon_id'=>$datas['member_coupon_id']])->find();
            if($coupon){
                $coupon = $coupon->toArray();
                $youhui[] = [
                    'discount_name'=>$coupon['couponInfo']['name'],
                    'discount_price'=>$datas['coupon_money']
                ];
                $youhui_name.='/券抵扣';
            }
        }
        //会员折扣
        if($datas['discount_detail']>0){
            $youhui_name.='/会员折扣';
            $youhui[] = [
                'discount_name'=>$datas['discount_detail'].'折',
                'discount_price'=>$datas['balance']/$datas['discount_detail']-$datas['balance']
            ];
        }
        $return = [
            'youhui_name'=>$youhui_name!=''?substr($youhui_name,1):'',
            'youhui'=>$youhui,
        ];

        return $return;
    }
}
